/**
 * 公共类
 */ //转换有问题的富文本
function changeHtml(str) {
    var htmlTxt = str.replace(/contenteditable/g, '');
    //去除table表格
    // htmlTxt=htmlTxt.replace(/span/g, "h2w-light");
    htmlTxt = htmlTxt.replace(/table/g, 'tr');
    // htmlTxt=htmlTxt.replace(/table/g, "h2w__tbody");
    //图片可以展示
    return htmlTxt.replace(/bollw:/g, 'http://api.bolledu.net/boll-api/ques_net/');
}
//基础库版本号比较
function compareVersion(v1, v2) {
    v1 = v1.split('.');
    v2 = v2.split('.');
    const len = Math.max(v1.length, v2.length);
    while (v1.length < len) {
        v1.push('0');
    }
    while (v2.length < len) {
        v2.push('0');
    }
    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i]);
        const num2 = parseInt(v2[i]);
        if (num1 > num2) {
            return 1;
        } else if (num1 < num2) {
            return -1;
        }
    }
    return 0;
}
// 返回一个使用key切割str后的数组，key仍在数组中
function getHilightStrArray(str, key) {
    return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
}
//任务分析的时间
function getAllTime() {
    var timeJson = {};
    var oneDayMillions = 86400000; //一天的毫秒数
    var nowTimestamp = Date.parse(new Date());
    var time1 = nowTimestamp - oneDayMillions * 30; //30天前
    var time2 = nowTimestamp - oneDayMillions * 90; //3个月前
    var time3 = nowTimestamp - oneDayMillions * 180; //半年前
    var time4 = nowTimestamp - oneDayMillions * 7; //7天前
    var time5 = nowTimestamp - oneDayMillions * 1; //1天前
    var day1 = new Date(time1);
    var day2 = new Date(time2);
    var day3 = new Date(time3);
    var day4 = new Date(time4);
    var day5 = new Date(time5);
    timeJson.time1 = day1.getFullYear() + '-' + (day1.getMonth() + 1) + '-' + day1.getDate() + ' ' + day1.getHours() + ':' + day1.getMinutes() + ':' + day1.getSeconds();
    timeJson.time2 = day2.getFullYear() + '-' + (day2.getMonth() + 1) + '-' + day2.getDate();
    timeJson.time3 = day3.getFullYear() + '-' + (day3.getMonth() + 1) + '-' + day3.getDate();
    timeJson.time4 = day4.getFullYear() + '-' + (day4.getMonth() + 1) + '-' + day4.getDate() + ' ' + day4.getHours() + ':' + day4.getMinutes() + ':' + day4.getSeconds();
    timeJson.time5 = day5.getFullYear() + '-' + (day5.getMonth() + 1) + '-' + day5.getDate() + ' ' + day5.getHours() + ':' + day5.getMinutes() + ':' + day5.getSeconds();
    return timeJson;
}
//获取时间戳 秒
function getTimestamp() {
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    return timestamp;
}
//获取时间戳 毫秒
function getTimestamp2() {
    var timestamp = Date.parse(new Date());
    timestamp = timestamp;
    return timestamp;
}
//时间转时间戳
function changeTimestamp(time) {
    var timestamp = Date.parse(new Date(time.replace(/-/g, '/')));
    timestamp = timestamp / 1000;
    return timestamp;
}
//字符串转时间
// that.data.end_time=(util.formatTime(new Date((that.data.loginData.end_time)*1000))).time8

//修改时间类型YYYY-MM为YYYY年MM月
// function changeTimeType(data) {
//   var newdata = ""
//   newdata = data.replace("-", "年")
//   return newdata + "月"
// }
function changeTimeType(data) {
    var newdata = '';
    newdata = data.replace(/-/g, '.');
    return newdata;
}
//分转换为秒
function changeTime(time) {
    var minute = 0;
    var second = 0;
    if (time.length == 2 && time.indexOf('秒') >= 0) {
        //只有2秒这种情况
        second = parseInt(time.substring(0, 1));
    }
    if (time.length == 3 && time.indexOf('秒') >= 0) {
        //只有2秒这种情况
        second = parseInt(time.substring(0, 2));
    }
    if (time.length > 6) {
        minute = parseInt(time.substring(0, 2));
        second = parseInt(time.substring(4, 6));
    }
    return minute * 60 + second;
}
function getDay(month) {
    var lastDay = '30';
    if (
        month == '01' ||
        month == '03' ||
        month == '05' ||
        month == '07' ||
        month == '08' ||
        month == '10' ||
        month == '12' ||
        month == '1' ||
        month == '3' ||
        month == '5' ||
        month == '7' ||
        month == '8'
    ) {
        lastDay = '31';
    } else if (month == '02' || month == '2') {
        lastDay = '28';
    }
    return lastDay;
}
// module.exports.getTimestamp = getTimestamp;
//界面跳转  转译 &为@
function filterand1(name) {
    var str = name.replace(/\&/g, '@');
    return str;
}
function filterand2(name) {
    var str = name.replace(/\@/g, '&');
    return str;
}
//上传参数
function json2Form(json) {
    var str = [];
    for (var p in json) {
        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(json[p]));
    }
    return str.join('&');
}

//生成uuid
function setuuid() {
    var s = [];
    var hexDigits = '0123456789abcdef';
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 16), 1);
    }
    s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 3) | 8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-';
    var uuid = s.join('');
    // uuid="d44281e3-8360-4cf6-87c3-f5a5cdd8"
    return uuid;
}
//生成token
function settoken() {
    var s = [];
    var hexDigits = '0123456789abcdef';
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 16), 1);
    }
    s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 3) | 8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-';
    var token = s.join('');
    return token.substring(0, 16);
}

//获取总的分页数
function getTotalPages(perPage, totalNum) {
    // 计算出多少页，采用ceil函数，返回不小于该数的最小整数 如 :6.1 返回7.0
    var totalPages = Math.ceil((totalNum * 1) / perPage);
    return totalPages;
}

/** 替换emoji表情 为空
 * 上传素材界面用
 */

function filterEmoji(name) {
    var str = name.replace(
        /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi,
        ''
    );
    return str;
}
/**替换空格键 */
function filterSpace(name) {
    var str = name.replace(/\s+/g, '');
    return str;
}
/**替换换行\n */
// var Str = "123  4556 66666\n\n\n";
// var reg1 = new RegExp('\n', 'g');
//  Str = Str.replace(reg1, '');
// console.log('替换换行符:' + Str);
/**
 * 替换特殊符号
 */
function filterSymbol(name) {
    var str = name.replace(/[`~!@#$%^&*()+=|{}:;,\[\].<>/?~！@#￥%……& ;*（）——+|{}【】；：”“’。，. 、？|-]/g, '');
    return str;
}
/**
 * 清除下载base64图片产生的缓存文件
 */
function clearBase64Path() {
    var aa = uni.getFileSystemManager();
    const basepath = uni.env.USER_DATA_PATH;
    aa.readdir({
        dirPath: basepath,
        /// 获取文件列表
        success(res) {
            // console.log(res.files)
            // console.log(res.files.length)
            res.files.forEach((val) => {
                // 遍历文件列表里的数据
                console.log(val);
                aa.unlink({
                    //删除
                    filePath: basepath + '/' + val
                });
            });
        },
        fail(err) {
            // console.log(err)
        },
        complete() {
            // console.log('complete')
        }
    });
}

//分解英文句子
function getImg(imgUrl) {
    var img = [];
    if (imgUrl.indexOf(',') >= 0) {
        var list = imgUrl.split(',');
        img = list;
    } else {
        img.push(imgUrl);
    }
    return img;
}

//分解英文句子
function getSentences(sentences) {
    var list = sentences.split(' ');
    return list;
}
//分解文章单词 articlieContent：文章
function getWordList(articlieContent) {
    var list = [];
    if (articlieContent.length > 0) {
        var reg = new RegExp('\n\n', 'g');
        var reg2 = new RegExp('\n', 'g');
        var str2 = articlieContent;
        if (str2.indexOf('\n\n') >= 0) {
            str2 = str2.replace(reg, ' ');
        }
        if (str2.indexOf('\n') >= 0) {
            str2 = str2.replace(reg2, ' ');
        }
        if (str2.indexOf(' ') >= 0) {
            list = str2.split(' ');
        }
    }
    return list;
}
function getpPragraph(articlieContent) {
    var list = [];
    if (articlieContent.length > 0) {
       
        var str2 = articlieContent;
        if (str2.indexOf('\n') >= 0) {
            list = str2.split('\n');
        }else{
			list.push(articlieContent)
		}
    }
    return list;
}
//分解单词数组：一个总数组分成两篇文章的单词
function getkeyWords(keyWords, articleId) {
    var list = [];
    keyWords.forEach((item, index) => {
        if (item.articleId == articleId) {
            list.push(item);
        }
    });
    return list;
}
// 文章单词是否是返回的待训练单词
// articlieWord:文章单词  word:待训练单词
function comparWord(articlieWord, wordList) {
    var result = false;
    if (!articlieWord) {
        return result;
    } // 如果字符串为空，直接返回
    //首字母如果是大写转化成小写
    articlieWord = articlieWord.charAt(0).toLowerCase() + articlieWord.slice(1);
    for (var i = 0; i < wordList.length; i++) {
        if (articlieWord.indexOf(wordList[i].original) >= 0) {
            result = true;
            break;
        }
    }
    return result;
}
//数字转换成汉字
function getHanZi(posi) {
    var list = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
    return list[posi];
}
//获得学历值等级
function getLevel(studyValue) {
    var item = {};
    var level = 1;
    var levelName = '';
    if (studyValue <= 350) {
        level = 1;
        levelName = 'A1';
    } else if (studyValue > 350 && studyValue <= 750) {
        level = 2;
        levelName = 'A2';
    } else if (studyValue > 750 && studyValue <= 1500) {
        level = 3;
        levelName = 'A3';
    } else if (studyValue > 1500 && studyValue <= 3500) {
        level = 4;
        levelName = 'A4';
    } else if (studyValue > 3500 && studyValue <= 4500) {
        level = 5;
        levelName = 'A5';
    } else if (studyValue > 4500 && studyValue <= 5500) {
        level = 6;
        levelName = 'A6';
    } else if (studyValue > 5500 && studyValue <= 6000) {
        level = 7;
        levelName = 'A7';
    } else if (studyValue > 6000) {
        level = 8;
        levelName = 'A8';
    }
    item.posi = level;
    item.name = levelName;
    return item;
}
//创建用户学习行为数据

function setUserInfos() {
    var userArticleInfos = [];
    for (var i = 1; i < 6; i++) {
        var item = {};
        item.type = i; //
        item.quesCount = 0; //题目数量
        item.rightCount = 0; //题目正确数量
        item.countList = [];
        item.useTime = 0; //模块使用时长(秒)
        item.useTimeList = []; //模块使用时长(时间戳)[{开始时间，结束时间}]
        // if (i == 1) {//先创建阅读文章的开始时间
        //     var userItem = {}
        //     userItem.startIime = getTimestamp()//现在的时间
        //     userItem.endIime = 0
        //     item.useTimeList.push(userItem)
        // }
        userArticleInfos.push(item);
    }
    return userArticleInfos;
}
//编辑用户学习行为数据(编辑时间)
//type/loadigType 1-阅读(阅读文章1+阅读理解2（题目）)；2-听力（选词1、组句2）；3-口语；4-词汇（单词学习0（有时间没题目）英选中1、中选英2、选词填空3、单词复习4（有时间没题目））；5-词汇听写（只包含听写）
//posi 0-开始 1-结束
//quesCount 题目数量
//rightCount 题目正确数量
function editUserInfos(type, posi, list, quesCount, rightCount) {
    var userArticleInfos = list;
    for (var i = 0; i < userArticleInfos.length; i++) {
        if (i + 1 == type) {
            var item = userArticleInfos[i];
            var TimeList = item.useTimeList;
            var timeItem = {};
            if (quesCount > 0) {
                userArticleInfos[i].quesCount += quesCount;
            }
            if (rightCount > 0) {
                userArticleInfos[i].rightCount += rightCount;
            }
            if (posi == 0) {
                //开始时间
                timeItem.startIime = getTimestamp(); //现在的时间
                userArticleInfos[i].useTimeList.push(timeItem);
            } else {
                //结束时间
                if (TimeList.length > 0) {
                    timeItem = TimeList[TimeList.length - 1];
                }
                timeItem.endIime = getTimestamp(); //现在的时间

                userArticleInfos[i].useTimeList[TimeList.length - 1] = timeItem;
            }
        }
    }
    return userArticleInfos;
}
module.exports = {
    changeHtml: changeHtml,
    compareVersion: compareVersion,
    getTimestamp: getTimestamp,
    getTimestamp2: getTimestamp2,
    changeTimestamp: changeTimestamp,
    getHilightStrArray: getHilightStrArray,
    json2Form: json2Form,
    setuuid: setuuid,
    settoken: settoken,
    getTotalPages: getTotalPages,
    changeTimeType: changeTimeType,
    filterEmoji: filterEmoji,
    filterSpace: filterSpace,
    clearBase64Path: clearBase64Path,
    filterand1: filterand1,
    filterand2: filterand2,
    filterSymbol: filterSymbol,
    getAllTime: getAllTime,
    getDay: getDay,
    getImg: getImg,
    getWordList: getWordList,
	getpPragraph:getpPragraph,
    getkeyWords: getkeyWords,
    getSentences: getSentences,
    getHanZi: getHanZi,
    getLevel: getLevel,
    setUserInfos: setUserInfos,
    editUserInfos: editUserInfos,
    changeTime: changeTime,
    comparWord: comparWord
};
